package org.grow.present.controller.auth;

import lombok.extern.slf4j.Slf4j;
import org.grow.present.domain.Company;
import org.grow.present.dto.Msg;
import org.grow.present.exception.MissTargetException;
import org.grow.present.interceptor.AuthInterceptor;
import org.grow.present.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/wx")
public class WxLoginController {
    @Autowired
    private JwtService jwtService;
    @Autowired
    private WxLoginService wxLoginService;
    //    @Autowired
//    private UserInfoService userInfoService;
    @Autowired
    private CompanyService companyService;

    @PostMapping("/login")
    public Msg<Map<String, Object>> login(@RequestParam("code") String code) {
        System.out.println("微信登录获取的临时code:" + code);
        String openid = wxLoginService.login(code);
        if (!StringUtils.hasText(openid)) {
            throw new MissTargetException("获取openid 失败");
        }
        System.out.println("wx - uid : " + openid);
//        此处可能不止一张表 跟注册初始化逻辑差不多
//        UserInfo userInfo = userInfoService.forceGet(openid);
        Company company = companyService.forceGet(openid);

        HashMap<String, Object> map = new HashMap<>();
        map.put("UID", company.getComId());
        String token = jwtService.createToken(map);
        HashMap<String, Object> returned = new HashMap<>();
        returned.put("token", token);
        return Msg.success().data(returned);
    }

    @GetMapping("/currentUID")
    public Msg currentUID() {
        System.out.println("----测试登录完整性当前用户--" + AuthInterceptor.getUID());
        return Msg.success().data(AuthInterceptor.getUID());
    }
}
